package com.wangnan.consumer.controller;

import com.netflix.appinfo.InstanceInfo;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
public class UserController {

    @Autowired
    LoadBalancerClient loadBalancerClient;

    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    RestTemplate template;

    AtomicInteger atomicInteger;

    /**
     * 使用ribbon负载调用
     * @return
     */

    @GetMapping("client1")
    public String getClient1(){
        ServiceInstance instance = loadBalancerClient.choose("provider");
        String url = "http://"+instance.getHost()+":"+instance.getPort()+"/hi";
        System.out.println(url);
        String respStr = template.getForObject(url,String.class);
        System.out.println(respStr);
        return respStr;
    }
    @GetMapping("client2")
    public String getClient2(){
        //获取注册中心服务列表
        List<ServiceInstance> instances = discoveryClient.getInstances("provider");
        for (ServiceInstance ins : instances) {
            System.out.println(ToStringBuilder.reflectionToString(ins));
        }
        String respStr = null;
        if(instances.size()>0) {
            //此处可自定义负载算法，随机
            //new Random().nextInt(instances.size());

            //负载
//            int i = atomicInteger.getAndIncrement();
//            int t = instances.size()%i;

            //权重
            // 服务
            InstanceInfo instanceInfo = (InstanceInfo) instances.get(0);
            if(instanceInfo.getStatus() == com.netflix.appinfo.InstanceInfo.InstanceStatus.UP) {

                String url =	"http://" + instanceInfo.getHostName() +":"+ instanceInfo.getPort() + "/hi";

                System.out.println("url:" + url);

                respStr = template.getForObject(url, String.class);

                System.out.println("respStr"  + respStr);
            }

        }
        return respStr;
    }
}
